package online.zhangwenzhe.blog.api.authorization.oauth2;

import online.zhangwenzhe.blog.api.authorization.UserVerification.UserVerification;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;

import java.util.HashMap;

@Component
public class MyAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    @Qualifier("PasswordUserVerificationImpl")
    UserVerification passwordUserVerificationImpl;

    @Autowired
    @Qualifier("SmsUserVerificationImpl")
    UserVerification smsUserVerificationImpl;

    public UserVerification getUserVerification(String type) {
        if (type.equals("sms")) {
            return smsUserVerificationImpl;
        }
        if (type.equals("pwd")) {
            return passwordUserVerificationImpl;
        }
        return null;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        HashMap<String, String> details = (HashMap<String, String>) authentication.getDetails();
        String scope = details.get("scope");
        UserVerification userVerification = getUserVerification(scope);
        User user = userVerification.verifiy(authentication.getPrincipal().toString(), authentication.getCredentials().toString());
        if (user == null) {
            throw new MyAuthenticationException("验证失败");
        }

        return new UsernamePasswordAuthenticationToken(user.getId(), user.getPassword(), user.getAuthorities());
//        return new UsernamePasswordAuthenticationToken(authentication.getPrincipal(), authentication.getCredentials(), authentication.getAuthorities());
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return UsernamePasswordAuthenticationToken.class.equals(aClass);
    }
}
